import { equ } from '../../../../package-env'
import { transformImage } from '@/utils/client'
import { useUIStore } from '@/store/ui'
import { useTtsaStore } from '@/store/ttsa'

const ttsa = useTtsaStore()
const UIStore = useUIStore()
const UIList = computed(() => UIStore.container as any)
const getContent = (data) => {
  if (!data) return ''
  return data.replace(/\\n/g, '<br>')
}

const getImage = (cfg) => {
  // 是否是Apng图片
  const isApng = Boolean(cfg.apng === 'true' || cfg.webp_url)
  return transformImage(cfg.webp_url || cfg.data, isApng)
}

const music = new Audio(
  new URL(`../../../assets/music/button-feedback.mp3`, import.meta.url).href
)
music.volume = 0.5

const getChild = (cfg, onLoad, id) => {
  const { type, data, autoplay, style, muted, inner_round, cover_url } = cfg

  let res = null
  let round = null
  if (inner_round) {
    round = `border-radius: ${inner_round}; overflow: hidden;`
  }
  switch (type) {
    case 'widget_pic':
      res = (
        <div class="ui-image w-full h-full" style={round}>
          <img
            onLoad={onLoad}
            src={getImage(cfg)}
            alt=""
            class="h-full w-full"
          />
        </div>
      )
      break
    case 'widget_text':
      res = <div class="ui-text scroll max-h-[220px]">{getContent(data)}</div>
      break
    case 'widget_singlevideo':
      const attr: LooseObject = {}
      if (autoplay !== 'false') attr.autoplay = 'true'
      if (equ === 'h5' && muted !== 'false') attr.muted = 'true'
      res = (
        <video
          class={[
            'h-full w-full object-cover',
            cfg['border_type'] === 'fillet' ? 'rounded-[24px]' : ''
          ]}
          style={round}
          src={data}
          {...attr}
          id={id}
          poster={transformImage(cover_url)}
          x5-playsinline="h5-page"
          x-webkit-airplay="allow"
          webkit-playsinline="true"
          playsinline="true"
          controls={style['z-index'] ? false : true}
        />
      )
      break
  }
  return res
}

const skip = (cfg) => {
  const onSkipClick = (event) => {
    event.stopPropagation()
    if (!cfg || !cfg?.event_click) return
    UIStore.go(cfg?.event_click)
  }
  return (
    <div
      class="skip absolute -bottom-46px right-0 bg-[#7599BF] bg-opacity-50 py-5px px-12px text-12px rounded-10px cursor-pointer"
      onClick={onSkipClick}
    >
      {ttsa.is_return_peek && cfg['label-again']
        ? cfg['label-again']
        : cfg.label || '跳过'}
    </div>
  )
}

export default function useChild(props: {
  cfg: LooseObject
  load: LooseFunction
  id: string
}) {
  // 字幕控件存在 不需要播放音效
  const isHaveSubtitle = Object.keys(UIList.value).find(
    (i) => UIList.value[i].type === 'widget_subtitle'
  )
  if (music.play && !isHaveSubtitle) music.play()
  return (
    <div class="ui-child z-2 relative h-full w-full">
      {getChild(props.cfg, props.load, props.id)}
      {props.cfg.skip ? skip(props.cfg.skip) : null}
    </div>
  )
}
